/**
 * 
 * AxLoopList
 * 
 * Author: WaveF
 * QQ: 298010937
 * 
 * TODO:
 * v0.2.0
 * - [x] 鼠标移入时滚动暂停
 * - [x] 对外暴露更多动画参数
 * 
 **/

(function () {

  let el, size, move, step;
  let animeOpts = {};

  main();

  function main() {
    yepnope({
      test: window.anime,
      nope: 'https://ax.minicg.com/anime.min.js',
      complete: inited
    });
  }

  function inited() {
    if (!window.axlib) {
      console.log('你需要先加载axlib!');
      return;
    }
    axlib.loopList = loopList;
  }

  function loopList(repeater, options) {
    this.version = { name: 'axlooplist', version: '0.2.0' };

    options = options || { move:'item', delay:0, endDelay:500, duration:1000, easing:'easeOutCubic' };

    move = options.move;
    animeOpts.delay = options.delay || 0;
    animeOpts.endDelay = options.endDelay || 500;
    animeOpts.duration = options.duration || 1000;
    animeOpts.easing = options.easing || 'easeOutCubic';

    el = repeater.getEl();
    let data = repeater.getRepeaterData();

    size = {
      width: $(el).width(),
      height: $(el).height()
    };
    let itemHeight = repeater.$().children('div').eq(0).height();

    // 必须在设置 size 后再添加新数据，否则记录的初始尺寸不对
    data = data.concat(data);
    repeater.setRepeaterData(data);

    if (move === 'full') {
      step = size.height;
    } else if (move === 'item') {
      step = Math.abs(move) || itemHeight;
    }

    tween();

    return this;
  }

  function tween() {
    let { delay, endDelay, duration, easing } = animeOpts;
    let anim = anime({
      targets: el,
      top: {
        value: `-=${step}`,
        delay,
        endDelay,
        duration,
      },
      easing,
      complete: an => {
        let posY = $(el).position().top;
        if (posY == -size.height) {
          el.style.top = 0;
        }
        $(el).unbind('mouseover mouseout');
        tween();
      }
    });

    $(el).mouseover(e=>{ anim.pause(); });
    $(el).mouseout(e=>{ anim.play(); });
  };
}());